package com.hyk.commonLib.common.utils;

import android.Manifest;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;

import com.hyk.commonLib.common.activity.BaseActivity;
import com.hyk.commonLib.common.utils.rx.activityResult.ActivityResultCompat;
import com.hyk.commonLib.common.utils.rx.activityResult.RxActivityResult;

import java.lang.reflect.Method;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.functions.Function;


/**
 * Created by 贺玉琨 on 2020/9/9.
 */
public class SystemAlertWindowPermissionUtils {
    private static final int OP_SYSTEM_ALERT_WINDOW = 24;

    public static boolean check() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return Settings.canDrawOverlays(AppUtils.getAppContext());
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            return checkOp(OP_SYSTEM_ALERT_WINDOW);
        } else {
            return true;
        }
    }

    public static Observable<Boolean> request(BaseActivity<?> activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Intent intent = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + AppUtils.getAppContext().getPackageName()));
                if (!AppUtils.isIntentAvailable(intent)) intent = null;
            }
            if (intent == null) {
                intent = getManageDrawOverlaysIntentForRom();
            }
            return intent == null ? Observable.just(false) : RxActivityResult.get(activity)
                    .start(intent)
                    .toObservable()
                    .flatMap((Function<ActivityResultCompat, ObservableSource<Boolean>>) activityResult -> Observable.just(check()));
        }
        AppOpsManager manager = (AppOpsManager) AppUtils.getAppContext().getSystemService(Context.APP_OPS_SERVICE);
        try {
            Method method = AppOpsManager.class.getDeclaredMethod("setMode", int.class, int.class, String.class, int.class);
            method.invoke(manager, OP_SYSTEM_ALERT_WINDOW, Binder.getCallingUid(), AppUtils.getAppContext().getPackageName(), AppOpsManager.MODE_ALLOWED);
            return Observable.just(true);
        } catch (Exception ignored) {

        }
        return Observable.just(false);
    }

    private static boolean checkOp(int op) {
        AppOpsManager manager = (AppOpsManager) AppUtils.getAppContext().getSystemService(Context.APP_OPS_SERVICE);
        try {
            Method method = AppOpsManager.class.getDeclaredMethod("checkOp", int.class, int.class, String.class);
            return AppOpsManager.MODE_ALLOWED == (int) method.invoke(manager, op, Binder.getCallingUid(), AppUtils.getAppContext().getPackageName());
        } catch (Exception ignored) {
        }
        return false;
    }

    private static Intent getManageDrawOverlaysIntentForRom() {
        if (RomUtils.isMiui()) {
            return getManageDrawOverlaysIntentForMiui();
        }
        if (RomUtils.isEmui()) {
            return getManageDrawOverlaysIntentForEmui();
        }
        if (RomUtils.isFlyme()) {
            return getManageDrawOverlaysIntentForFlyme();
        }
        if (RomUtils.isOppo()) {
            return getManageDrawOverlaysIntentForOppo();
        }
        if (RomUtils.isVivo()) {
            return getManageDrawOverlaysIntentForVivo();
        }
        if (RomUtils.isSmartisan()) {
            return getManageDrawOverlaysIntentForSmartisan();
        }
        return null;
    }

    // 小米
    private static Intent getManageDrawOverlaysIntentForMiui() {
        Intent intent = new Intent("miui.intent.action.APP_PERM_EDITOR");
        intent.putExtra("extra_pkgname", AppUtils.getAppContext().getPackageName());
        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.AppPermissionsEditorActivity");
        if (AppUtils.isIntentAvailable(intent)) {
            return intent;
        }
        intent.setClassName("com.miui.securitycenter", "com.miui.permcenter.permissions.PermissionsEditorActivity");
        if (AppUtils.isIntentAvailable(intent)) {
            return intent;
        }
        // miui v5 的支持的android版本最高 4.x
        // http://www.romzj.com/list/search?keyword=MIUI%20V5#search_result
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.fromParts("package", AppUtils.getAppContext().getPackageName(), null));
            if (AppUtils.isIntentAvailable(intent)) {
                return intent;
            }
        }
        return null;
    }

    private final static String HUAWEI_PACKAGE = "com.huawei.systemmanager";

    // 华为
    private static Intent getManageDrawOverlaysIntentForEmui() {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            intent.setClassName(HUAWEI_PACKAGE, "com.huawei.systemmanager.addviewmonitor.AddViewMonitorActivity");
            if (AppUtils.isIntentAvailable(intent)) {
                return intent;
            }
        }
        // Huawei Honor P6|4.4.4|3.0
        intent.setClassName(HUAWEI_PACKAGE, "com.huawei.notificationmanager.ui.NotificationManagmentActivity");
        intent.putExtra("showTabsNumber", 1);
        if (AppUtils.isIntentAvailable(intent)) {
            return intent;
        }
        intent.setClassName(HUAWEI_PACKAGE, "com.huawei.permissionmanager.ui.MainActivity");
        if (AppUtils.isIntentAvailable(intent)) {
            return intent;
        }
        return null;
    }

    // VIVO
    private static Intent getManageDrawOverlaysIntentForVivo() {
        // 不支持直接到达悬浮窗设置页，只能到 i管家 首页
        Intent intent = new Intent("com.iqoo.secure");
        intent.setClassName("com.iqoo.secure", "com.iqoo.secure.MainActivity");
        // com.iqoo.secure.ui.phoneoptimize.SoftwareManagerActivity
        // com.iqoo.secure.ui.phoneoptimize.FloatWindowManager
        if (AppUtils.isIntentAvailable(intent)) {
            return intent;
        }
        return null;
    }

    // OPPO
    private static Intent getManageDrawOverlaysIntentForOppo() {
        Intent intent = new Intent();
        intent.putExtra("packageName", AppUtils.getAppContext().getPackageName());
        // OPPO A53|5.1.1|2.1
        intent.setAction("com.oppo.safe");
        intent.setClassName("com.oppo.safe", "com.oppo.safe.permission.floatwindow.FloatWindowListActivity");
        if (AppUtils.isIntentAvailable(intent)) {
            return intent;
        }
        // OPPO R7s|4.4.4|2.1
        intent.setAction("com.color.safecenter");
        intent.setClassName("com.color.safecenter", "com.color.safecenter.permission.floatwindow.FloatWindowListActivity");
        if (AppUtils.isIntentAvailable(intent)) {
            return intent;
        }
        intent.setAction("com.coloros.safecenter");
        intent.setClassName("com.coloros.safecenter", "com.coloros.safecenter.sysfloatwindow.FloatWindowListActivity");
        if (AppUtils.isIntentAvailable(intent)) {
            return intent;
        }
        return null;
    }

    // 魅族
    private static Intent getManageDrawOverlaysIntentForFlyme() {
        Intent intent = new Intent("com.meizu.safe.security.SHOW_APPSEC");
        intent.setClassName("com.meizu.safe", "com.meizu.safe.security.AppSecActivity");
        intent.putExtra("packageName", AppUtils.getAppContext().getPackageName());
        if (AppUtils.isIntentAvailable(intent)) {
            return intent;
        }
        return null;
    }

    // 锤子
    private static Intent getManageDrawOverlaysIntentForSmartisan() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return null;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 锤子 坚果|5.1.1|2.5.3
            Intent intent = new Intent("com.smartisanos.security.action.SWITCHED_PERMISSIONS_NEW");
            intent.setClassName("com.smartisanos.security", "com.smartisanos.security.SwitchedPermissions");
            intent.putExtra("index", 17); // 不同版本会不一样
            if (AppUtils.isIntentAvailable(intent)) {
                return intent;
            }
        } else {
            // 锤子 坚果|4.4.4|2.1.2
            Intent intent = new Intent("com.smartisanos.security.action.SWITCHED_PERMISSIONS");
            intent.setClassName("com.smartisanos.security", "com.smartisanos.security.SwitchedPermissions");
            intent.putExtra("permission", new String[]{Manifest.permission.SYSTEM_ALERT_WINDOW});

            //        Intent intent = new Intent("com.smartisanos.security.action.MAIN");
            //        intent.setClassName("com.smartisanos.security", "com.smartisanos.security.MainActivity");
            if (AppUtils.isIntentAvailable(intent)) {
                return intent;
            }
        }
        return null;
    }

}
